<template>
  <div class="p-sm box-border">
    <div>
      <div class="my-sm">
        <a-button @click="addShow = true">新增</a-button>
      </div>
      <a-table
        row-key="id"
        :data="tableData"
        :columns="columns"
        :pagination="menuStore().pagination"
      >
      </a-table>
    </div>

    <add-menu
      :menuTree="menuTree"
      v-model:visible="addShow"
      v-if="addShow"
    ></add-menu>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { menuStore } from "@/store/menu/index";
import { getmenuList } from "@/api/menu";
import { Message } from "@arco-design/web-vue";
import AddMenu from "./component/add-menu.vue";

const tableData = ref([{ menuName: "kkk" }]);
const addShow = ref(false);
const menuTree = ref();
const columns = ref([
  {
    title: "菜单名称",
    dataIndex: "menuName",
    width: 70,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "图标",
    width: 70,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "排序",
    dataIndex: "orderNum",
    width: 70,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "组件路径",
    width: 70,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "创建时间",
    width: 70,
    dataIndex: "createTime",
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "操作",
    width: 70,
    slotName: "operate",
  },
]);
const buildTree = (arr: any) => {
  const treeMap: any = {};

  arr.forEach((item: any) => {
    treeMap[item.id] = {
      id: item.id,
      p_id: item.p_id,
      menuName: item.menuName,
      createTime: item.createTime,
      icon: item.icon,
      orderNum: item.orderNum,
      url: item.url,
      children: [],
    };
  });

  // Step 2: Build relationships
  arr.forEach((item: any) => {
    if (item.p_id !== -1 && treeMap[item.p_id]) {
      treeMap[item.p_id].children.push(treeMap[item.id]);
    }
  });

  // Step 3: Find root nodes
  const roots = arr
    .filter((item: any) => item.p_id === -1)
    .map((item: any) => treeMap[item.id]);

  return roots;
};
const getList = async () => {
  try {
    let res = await getmenuList();
    if (res?.code == 200) {
      tableData.value = res.data;
      menuTree.value = buildTree(tableData.value);
      console.log(menuTree.value, " menuTree.value");
    } else {
      Message.error(res?.msg || "接口失败");
    }
  } catch (error) {
    console.error(error);
  }
};

getList();
</script>

<style lang="less" scoped></style>
